package cfs.controller;

/*
 * 
 To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cfs.databean.Fund;
import cfs.databean.FundPriceHistory;
import cfs.model.FundDAO;
import cfs.model.FundPriceHistoryDAO;
import cfs.model.Model;

/**
 * 
 * @author danny seow
 */
public class ViewFundListAction extends Action {
	private FundDAO fundDAO;
	private FundPriceHistoryDAO fundPriceDAO;
	private FundPriceHistoryManager fphm;

	public ViewFundListAction(Model model) {
		fundDAO = model.getFundDao();
		fundPriceDAO = model.getFundHistoryDao();
		fphm = new FundPriceHistoryManager();
	}

	@Override
	public String getName() {
		return "viewFundList.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			// Fetching the values from the database
			Fund[] fundList = fundDAO.getAll();
			if (fundList == null || fundList.length <= 0) {
				errors.add("No Fund items found");
			}
			if (errors.size() > 0)
				return "ViewFundListPage.jsp";
			
			FundPriceHistory[] fundPriceList = fundPriceDAO.getAll();
			HashMap resultDifference = null;
			ArrayList<FundPriceHistory> fundPriceListArray = null;
			if (fundPriceList != null && fundPriceList.length > 0) {
				if (fundPriceList.length > 1) {
					resultDifference = fphm
							.getLatestDifferenceList(fundPriceList);
					fundPriceListArray = fphm.sortFundList(fundPriceList);
				}
			}

			request.setAttribute("fundList", fundList);
			request.setAttribute("fundPriceList", fundPriceListArray);
			request.setAttribute("resultDifference", resultDifference);
			return "ViewFundListPage.jsp";
		} catch (Exception e) {
			errors.add("There is an error retrieving fund list");
			return "ViewFundListPage.jsp";
		}
	}

}
